package com.tedu.food.sys.service.impl;

import com.tedu.food.common.exception.ServiceException;
import com.tedu.food.sys.dao.CartItemDao;
import com.tedu.food.sys.dao.MemberDao;
import com.tedu.food.sys.entity.Member;
import com.tedu.food.sys.service.MemberService;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import java.util.UUID;

@Service
public class MemberServiceImpl implements MemberService {
	@Autowired
	private MemberDao memberDao;
	@Autowired
	private CartItemDao cartItemDao;
	
	    @Override
	    public int saveObject(Member entity, 
	    		Integer[] roleIds) {
	    	//1.参数检验
	    	if(entity==null)
	    		throw new IllegalArgumentException("保存对象不能为空");
	    	if(StringUtils.isEmpty(entity.getUsername()))
	    		throw new IllegalArgumentException("用户名不能为空");
	    	if(StringUtils.isEmpty(entity.getPassword()))
	    		throw new IllegalArgumentException("密码不能为空");
	    	//2.保存用户自身信息
	    	//2.1对密码进行md5盐值加密
	    	//获取一个盐值,这个值使用随机的字符串
	    	String salt=UUID.randomUUID().toString();
	    	//借助shiro框架中的API对应密码进行盐值加密
	    	SimpleHash sh=new SimpleHash(
	    			"MD5",//algorithmName 算法名(MD5算法是一种消息摘要算法)
	    			entity.getPassword(),//source 未加密的密码
	    			salt,//盐
	    			1);//hashIterations表示加密次数
	    	//将加密结果转成16进制
	    	String pwd=sh.toHex();
	    	//2.2将盐值和密码存储SysUser对象
	    	entity.setSalt(salt);
	    	entity.setPassword(pwd);
	    	//2.3将SysUser对象持久化到数据库
	    	int rows=memberDao.insertObject(entity);
	    	//3.给该用户加个购物车
			cartItemDao.insertCart(entity.getId());
	    	//4.返回结果
	    	return rows;
	    }

		@Override
		public Member findMemberByUsername(String username ) {
		
		  if(username == null || username.equals("") ) 
			  throw new  IllegalArgumentException("请先输入用户名");
		 
			
			Member member = memberDao.findMemberByUsername(username);
			if(member != null) 
				throw new ServiceException("该用户名已被注册");
			
			return member;
		}
		
		@Override
		public Member findMemberByPhone(String phone) {
			 if(phone == null || phone.equals("") ) 
				 throw new IllegalArgumentException("请先输入手机号");
			 
				
				Member phon = memberDao.findMemberByPhone(phone);
				if(phon != null) 
					throw new ServiceException("该手机号已被注册");
				
				return phon;
		}

}
